#encoding=utf-8
from django import forms

from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm

from django.utils.translation import ugettext_lazy, ugettext as _

from xadmin.util import User

ERROR_MESSAGE = ugettext_lazy("Please enter the correct username and password "
                              "for a staff account. Note that both fields are case-sensitive.")

from captcha.fields import CaptchaField
class AdminAuthenticationForm(AuthenticationForm):
    """
    A custom authentication form used in the admin app.

    """
    captcha= CaptchaField(error_messages={'required': ugettext_lazy("need captcha")})
    this_is_the_login_form = forms.BooleanField(
        widget=forms.HiddenInput, initial=1,
        error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")})


    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        #self.captcha.clean(1)
        #code = self.request.POST.get('captcha_1')
        #print self.request.POST
        #print self.data.get("captcha_0"),self.data.get("captcha_1")
        #value = [self.data.get("captcha_0"),self.data.get("captcha_1")]
        #response, value[1] = (value[1] or '').strip().lower(), ''
        #print self.cleaned_data.get("captcha")
        #print self.errors.get("captcha")
        if self.errors:
            raise forms.ValidationError(self.errors)
        #from captcha.models import CaptchaStore, get_safe_now
        #print response, value[0]
        #CaptchaStore.objects.get(response=response, hashkey=value[0], expiration__gt=get_safe_now())
        #self.fields["captcha"].clean([self.data.get("captcha_0"),self.data.get("captcha_1")])
        message = ERROR_MESSAGE
        #raise forms.ValidationError("code error")
        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        self.check_for_test_cookie()
        #更新代理登陆时间

        import datetime
        # if(AgentInfo.objects.filter(account=username).exists()):
        #     tip=self.request.META["REMOTE_ADDR"]
        #     if(tip.find(',')>0):
        #         tip=tip[0:tip.find(',')]
        #     AgentInfo.objects.filter(account=username).update(login_time=datetime.datetime.now(),login_ip=tip)
        return self.cleaned_data
